package two;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import one.pojo.MyValue;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 泛型
 * JAVA 的泛型胡进行类型擦除，所以无法获取运行时的类型，使用TypeReference 可以指定json串对应的类型
 * 在用于泛型容器时，特别有用
 */
public class GenericTypeExample {
    public static void main(String[] args) throws IOException {
        readJsonToList();
        readJsonToMap();
    }

    private static void readJsonToList() throws IOException {
        URL resource = GenericTypeExample.class.getClassLoader().getResource("two/genericList.json");
        ObjectMapper mapper = new ObjectMapper();
        List<MyValue> myValueList = mapper.readValue(resource, new TypeReference<List<MyValue>>() {
        });
        myValueList.forEach(System.out::println);
    }

    private static void readJsonToMap() throws IOException {
        URL resource = GenericTypeExample.class.getClassLoader().getResource("two/genericMap.json");
        ObjectMapper mapper = new ObjectMapper();
        Map<String, MyValue> myValueMap = mapper.readValue(resource, new TypeReference<Map<String, MyValue>>() {
        });
        myValueMap.entrySet().forEach(System.out::println);
    }

}
